﻿using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using AcceptServer.Service;
using Common;
using Model;

namespace AcceptServer
{
    public partial class AcceptMainForm : Form
    {
        public AcceptMainForm()
        {
            InitializeComponent();
            label_version.Text = StrVersion;
        }



        public static string ServerWebIp;
        //  private static string _serverLanIp;

        private const string StrVersion = "1.0.0";
        private readonly Hashtable _ipEndPointList = Hashtable.Synchronized(new Hashtable());
        private readonly Hashtable _ipEndPointTimeList = Hashtable.Synchronized(new Hashtable());


        readonly TQueue<byte[]> _dateQueue = new TQueue<byte[]>();

        private UdpServer _server;
        private UdpServer _server2;

        private Socket _udpClientChinaNet;
        private Socket _udpClientUniCom;
        private IPEndPoint _ipepChinaNet;
        private IPEndPoint _ipepUniCom;



        private Socket socketListener;


        private int _dataHandlerThreadCount = 1;
        private int _dataBaseHandlerThreadCount = 1;


        private Thread[] _threadDataHandler;//数据处理线程

        private Thread _ipEndPointClearThread;

        private Thread _tcpListene;

        // readonly IPEndPoint _ipep = new IPEndPoint(IPAddress.Any, ConstParameters.AstPort);
        private const string LocalhostIP = "127.0.0.1";


        // public static readonly Hashtable TaxiList = Hashtable.Synchronized(new Hashtable());
        public static readonly Hashtable BusiList = Hashtable.Synchronized(new Hashtable());

        private DataSet StationsBusDs;

        //!--1
        private void StartServecie()
        {
            //----save config
            string[] config = new string[2];
            config[0] = textBox_ChinaNetIp.Text;
            config[1] = textBox_UnicomIp.Text;
            OperateConfig.SaveAcceptServerConfig(config);
            //if (InitWcfService(textBox_PosIP.Text))
            //{
            InitControlAfterStartService();

            try
            {
                StationsBusDs = CXmlFileToDataSet("s.xml");

                socketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint address = new IPEndPoint(IPAddress.Any, Common.ConstParameters.TcpListene);

                socketListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                //绑定tcp端口
                socketListener.Bind(address);
                //启动tcp监听，并设置请求队列最大长度，如果请求超过最大程度则客户端会产生像服务器没有监听端口一样的 “由于目标机器积极拒绝” 错误
                socketListener.Listen(0);

                _tcpListene = new Thread(TcpLinsten) { IsBackground = true };
                _tcpListene.Start();


                if (textBox_ChinaNetIp.Text != LocalhostIP)
                {
                    _server = new UdpServer(textBox_ChinaNetIp.Text, ConstParameters.AstPort);
                    _server.OnReceivedData += server_OnDataReceived;
                    _server.Start();
                }

                if (textBox_UnicomIp.Text != LocalhostIP)
                {
                    _server2 = new UdpServer(textBox_UnicomIp.Text, ConstParameters.AstPort);
                    _server2.OnReceivedData += server_OnDataReceived;
                    _server2.Start();
                }

                if (textBox_ChinaNetIp.Text != LocalhostIP)
                {
                    _ipepChinaNet = new IPEndPoint(IPAddress.Parse(textBox_ChinaNetIp.Text), ConstParameters.AstPort);
                    _udpClientChinaNet = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    _udpClientChinaNet.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    _udpClientChinaNet.Bind(_ipepChinaNet);
                }
                if (textBox_UnicomIp.Text != LocalhostIP)
                {
                    _ipepUniCom = new IPEndPoint(IPAddress.Parse(textBox_UnicomIp.Text), ConstParameters.AstPort);
                    _udpClientUniCom = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    _udpClientUniCom.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    _udpClientUniCom.Bind(_ipepUniCom);
                }



                this._threadDataHandler = new Thread[_dataHandlerThreadCount];
                for (int i = 0; i < _dataHandlerThreadCount; i++)
                {
                    this._threadDataHandler[i] = new Thread(UdpSendData);
                    this._threadDataHandler[i].Start();
                }


                _ipEndPointClearThread = new Thread(IpEndPointClear) { IsBackground = true, Name = "IPEndPointClearThread----------------------------------------------" }; ;
                _ipEndPointClearThread.Start();
            }
            catch (Exception ex)
            {
                InitControlAfterStopService();
                CommonRoutine.HandlingExceptions(ex, true);
                LogService.WriteLog("AcceptMainForm.cs-155");
            }

            //}
            //else
            //{
            //    MessageBox.Show(@"位置服务器连接失败！");
            //}



        }



        //!--3
        public void TcpLinsten()
        {
            try
            {
                while (true)
                {
                    Socket ss = socketListener.Accept();
                    Console.WriteLine("one Socket Accept");
                    Thread t = new Thread(RecieveData);
                    t.Start(ss);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }



        }



        public void RecieveData(object obj)
        {
            Socket tcpClient = obj as Socket;
            string IMEI = string.Empty;
            while (true)
            {
                if (tcpClient != null)
                {
                    byte[] receBuffer = new byte[100];

                    #region rece Data
                    try
                    {
                        int receDataLength = tcpClient.Receive(receBuffer);
                        Thread.Sleep(1);
                        if (receDataLength == 0)
                        {
                            break;
                        }

                        byte[] receData = new byte[receDataLength];
                        Array.Copy(receBuffer, 0, receData, 0, receData.Length);

                        if (receData.Length < 6) continue;

                        if (receData[0] == 0x78 && receData[1] == 0x78 && receData[receDataLength - 2] == 0x0D && receData[receDataLength - 1] == 0x0A)
                        {
                            string receStr = CommonRoutine.ByteToHexStr(receData);
                            Console.WriteLine(DateTime.Now.ToString() + "  Rece  " + receData.Length + "    0x" + receData[3].ToString("X2"));

                            Console.WriteLine(receStr);


                            byte[] sendbytes = new byte[]
                                                      {
                                                          0x78, 0x78, 0x05, 0x01, 0x00, 0x01, 0xD9, 0xDC, 0x0D, 0x0A
                                                      };

                            if (receData[3] == 0x01)
                            {
                                byte[] temp = new byte[8];
                                Array.Copy(receData, 4, temp, 0, 8);
                                IMEI = CommonRoutine.ByteToBcdString(temp);
                                BusInfo b = new BusInfo();
                                b.IMEI = IMEI;

                                b.BusName = "";
                                if (b.IMEI == "0868120100407581" || b.IMEI == "0868120103974678" ||
                                    b.IMEI == "0868120103974033" || b.IMEI == "0868120103971450")
                                {
                                    //一路内
                                    b.BusName = StationInfo.stationgNamesArray[1];
                                }
                                if (b.IMEI == "0868120103991037" || b.IMEI == "0868120103989536"
                                    || b.IMEI == "0868120103989874")
                                {
                                    //一路外
                                    b.BusName = StationInfo.stationgNamesArray[0];
                                }
                                if (b.IMEI == "0868120103991458" || b.IMEI == "0868120103989023"
                                    || b.IMEI == "0868120103973480")
                                {
                                    //二路
                                    b.BusName = StationInfo.stationgNamesArray[2];
                                }


                                b.PreStation = "";
                                b.CurrentStation = "";

                                BusiList[IMEI] = b;
                                tcpClient.Send(sendbytes);
                            }
                            else if (receData[3] == 0x12)
                            {
                                try
                                {
                                    #region 0x12

                                    BusInfo b = BusiList[IMEI] as BusInfo;
                                    if (b == null) continue;

                                    byte[] tempbytes = new byte[6];
                                    Array.Copy(receData, 4, tempbytes, 0, 6);
                                    string datatimeStr = "20";
                                    foreach (var VARIABLE in tempbytes)
                                    {
                                        datatimeStr += VARIABLE.ToString().PadLeft(2, '0');
                                    }



                                    Console.WriteLine(datatimeStr);
                                    DateTime d = DateTime.ParseExact(datatimeStr, "yyyyMMddHHmmss", null);
                                    TimeSpan timeSpan = new TimeSpan(DateTime.Now.Ticks - d.Ticks);
                                    if (timeSpan.TotalSeconds > 120)
                                        continue;
                                    //----------------
                                    b.UpdateTime = d;



                                    string tmpBinayStr = Convert.ToString(receData[10], 2);
                                    int gpsLength = Convert.ToInt16(tmpBinayStr.Remove(4), 2);
                                    int gpsCount1 = Convert.ToInt16(tmpBinayStr.Remove(0, 4), 2);

                                    Array.Reverse(receData, 11, 4);
                                    double Latitude = BitConverter.ToInt32(receData, 11) / (30000.0 * 60);
                                    //------------
                                    b.Latitude = Math.Round(Latitude, 6);
                                    //string sdsdsd = Latitude.ToString("0.000000");

                                    Array.Reverse(receData, 15, 4);
                                    double longitude = BitConverter.ToInt32(receData, 15) / (30000.0 * 60);
                                    //--------------
                                    b.Longitude = Math.Round(longitude, 6);


                                    b.Speed = receData[19];
                                    string tmpBinayStr2 = Convert.ToString(receData[20], 2).PadLeft(8, '0') +
                                        Convert.ToString(receData[21], 2).PadLeft(8, '0');
                                    //----------
                                    string sdsdsadsd = tmpBinayStr2.Remove(0, 6);
                                    b.Angle = Convert.ToInt16(tmpBinayStr2.Remove(0, 6), 2);
                                    string sdsdsds =DateTime.Now.ToString() + b.BusName +"-"+b.IMEI+"-"+ "   纬度：" + b.Latitude +
                                                            "  经度： " + b.Longitude + "   速度：" + b.Speed +
                                                     "   度数：" + b.Angle;
                                    CalculatorBusGpsInWhichStation(b);

                                    Console.WriteLine(sdsdsds);
                                    #endregion
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.Message);
                                }
                            }
                            else if (receData[3] != 0x01)
                            {
                                sendbytes[3] = receData[3];
                                Array.Copy(receData, receData.Length - 6, sendbytes, 4, 2);
                                SetCRC(ref sendbytes);

                                tcpClient.Send(sendbytes);
                            }




                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        tcpClient.Close();
                        break;
                    }
                    #endregion
                }
                else
                {
                    break;
                }
            }
            if(IMEI != string.Empty)
            {
                BusiList.Remove(IMEI);
            }
           // BusiList[IMEI] = b;
            Console.WriteLine("one Socket disAccept" + IMEI);

            if (tcpClient != null)
            {
                tcpClient.Close();
            }
        }



        private void CalculatorBusGpsInWhichStation(BusInfo b)
        {
            if (StationsBusDs != null)
            {

                try
                {
                    double minDistance = int.MaxValue;
                    int index = -1;

                    for (int i = 0; i < StationsBusDs.Tables[0].Rows.Count; i++)
                    {

                        double tmpLat = double.Parse(StationsBusDs.Tables[0].Rows[i]["lat"].ToString());
                        double tmpLng = double.Parse(StationsBusDs.Tables[0].Rows[i]["lng"].ToString());
                        double tmpDistance = CommonRoutine.GetDistanceBetweenTwoGps(b.Latitude, b.Longitude,
                                                                            tmpLat, tmpLng);

                        if (tmpDistance <= minDistance)
                        {
                            minDistance = tmpDistance;
                            index = i;
                        }
                    }
                    Console.WriteLine("minDistance   :" + minDistance);
                    if (index != -1 && minDistance < 120)
                    {
                        string stationName = StationsBusDs.Tables[0].Rows[index]["name"].ToString().Replace("1", "").Replace("A", "");
                        if (b.CurrentStation != stationName)
                        {

                            b.PreStation = b.CurrentStation;
                            b.CurrentStation = stationName;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }



            }
        }





        void server_OnDataReceived(object sender, EventArgs e)
        {
            SocketAsyncEventArgs socketAsyncEventArgs = e as SocketAsyncEventArgs;
            if (socketAsyncEventArgs != null)
            {
                if (socketAsyncEventArgs.BytesTransferred >= ConstParameters.MhLenth)
                {
                    byte[] receData = new byte[socketAsyncEventArgs.BytesTransferred];
                    Array.Copy(socketAsyncEventArgs.Buffer, 0, receData, 0, receData.Length);
                    byte[] realData = OperateAgreement.RestoreReceData(receData);



                    if (OperateAgreement.JudgeisCompleteData(realData))
                    {
                        string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);


                        if (phoneNumber.Length == 12 && phoneNumber.StartsWith("1"))
                        {
                            if (!_ipEndPointList.ContainsKey(phoneNumber))
                            {
                                string temp = phoneNumber.Remove(0, 1);
                                int tmpInt;
                                int.TryParse(temp, out tmpInt);
                                if (tmpInt > 0 && tmpInt < 10)
                                {
                                    string stationName = string.Empty;
                                    if (tmpInt == 1) stationName = "行政服务中心";
                                    if (tmpInt == 2) stationName = "汽车站";
                                    if (tmpInt == 3) stationName = "财政局";
                                    if (tmpInt == 4) stationName = "金贸广场";
                                    if (tmpInt == 5) stationName = "南昌大学";
                                    if (tmpInt == 6) stationName = "恒奥国际城";


                               //     string result = UnicomSMS.SendSMS("18602789588,18627704749,18679255357",
                                   //                     "公交站点ID号为：" + phoneNumber + "    " + stationName + "  与服务器连接成功，时间：" + DateTime.Now.ToString());
                                }
                            }
                        }

                        _ipEndPointTimeList[phoneNumber] = DateTime.Now;
                        _ipEndPointList[phoneNumber] = socketAsyncEventArgs.RemoteEndPoint;
                        _dateQueue.Enqueue(receData);
                    }

                }

            }


        }

        private void UdpSendData()
        {

            while (true)
            {
                if (_dateQueue.Count < 1)
                {
                    Thread.Sleep(1000);
                    continue;
                }

                byte[] receData;
                lock (_dateQueue)
                {
                    receData = _dateQueue.Dequeue();
                }



                byte[] realData = OperateAgreement.RestoreReceData(receData);
                string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

                Socket sendSocket = JudgeIsUnicomNumber(phoneNumber);
                IPEndPoint ipEndPoint = _ipEndPointList[phoneNumber] as IPEndPoint;
                if (ipEndPoint == null) continue;
                byte[] sendData = new byte[1];
                try
                {
                    OperateCmdData operateCmdData = new OperateCmdData(); ;
                    sendData = operateCmdData.AnalysisMessageId(realData, ipEndPoint.Address);
                }
                catch (Exception ex)
                {
                    CommonRoutine.HandlingExceptions(ex);
                    LogService.WriteLog("AcceptMainForm.cs-405");
                    continue;
                }
                #region Send Bytes

                if (sendData != null && sendData.Length >= ConstParameters.MhLenth)
                {
                    try
                    {
                        //  sendSocket.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);
                        //_server.SendData(sendData, ipEndPoint);
                        //_udpClientChinaNet.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);
                        //_udpClientUniCom.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);
                        SendDataToIPAddress(sendData, ipEndPoint, phoneNumber);
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("AcceptMainForm.cs-428");
                        continue;
                    }
                }
                #endregion

            }


            #region LogPrint
            LogService.WriteLog(Thread.CurrentThread.Name + "----Snen Thread 退出----");
            #endregion
        }

        private void SendDataToIPAddress(byte[] data, IPEndPoint ipEndPoint, string sendToPhoneNumber)
        {
            Socket sendSocket = JudgeIsUnicomNumber(sendToPhoneNumber);
            sendSocket.SendTo(data, data.Length, SocketFlags.None, ipEndPoint);

            //_udpClientChinaNet.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);
            //_udpClientUniCom.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);
        }

        public Socket JudgeIsUnicomNumber(string phoneNumber)
        {
            #region 单线服务器 处理
            //不会出现这种情况。两个都为空的话没程序就没有收发消息的流程。
            // if (_udpClientUniCom == null && _udpClientChinaNet == null) 
            if (_udpClientUniCom == null && _udpClientChinaNet != null)
            {
                _udpClientUniCom = _udpClientChinaNet;
                return _udpClientChinaNet;
            }
            if (_udpClientUniCom != null && _udpClientChinaNet == null)
            {
                _udpClientChinaNet = _udpClientUniCom;
                return _udpClientUniCom;
            }
            #endregion
            //130、131、132、145、155、156、185、186 
            if (phoneNumber.StartsWith("130") || phoneNumber.StartsWith("131") || phoneNumber.StartsWith("132") ||
                phoneNumber.StartsWith("145") || phoneNumber.StartsWith("155") || phoneNumber.StartsWith("156") ||
                phoneNumber.StartsWith("185") || phoneNumber.StartsWith("186"))
            {
                return _udpClientUniCom;
            }
            else
            {
                return _udpClientChinaNet;
            }
        }


        private void IpEndPointClear()
        {
            while (true)
            {
                Thread.Sleep(80 * 1000);
                DateTime now = DateTime.Now;
                ArrayList delKey = new ArrayList();
                lock (_ipEndPointTimeList.SyncRoot)
                {
                    foreach (DictionaryEntry dictionaryEntry in _ipEndPointTimeList)
                    {
                        DateTime updatatime = (DateTime)dictionaryEntry.Value;
                        TimeSpan timeSpan = new TimeSpan(now.Ticks - updatatime.Ticks);
                        if (timeSpan.TotalSeconds > 600)
                        {
                            delKey.Add(dictionaryEntry.Key);

                        }
                    }
                }

                foreach (string phoneNumber in delKey)
                {
                    try
                    {
                        if (phoneNumber.Length == 12 && phoneNumber.StartsWith("1"))
                        {
                            string temp = phoneNumber.Remove(0, 1);
                            int tmpInt;
                            int.TryParse(temp, out tmpInt);
                            if (tmpInt > 0 && tmpInt < 10)
                            {

                                string stationName = string.Empty;
                                if (tmpInt == 1) stationName = "行政服务中心";
                                if (tmpInt == 2) stationName = "汽车站";
                                if (tmpInt == 3) stationName = "财政局";
                                if (tmpInt == 4) stationName = "金贸广场";
                                if (tmpInt == 5) stationName = "南昌大学";
                                if (tmpInt == 6) stationName = "恒奥国际城";


                                //UnicomSMS.SendSMS("18602789588,18627704749,18679255357", "公交站点ID号为：" +
                                //    phoneNumber + "   " + stationName + "  与网络失去连接，时间：" + DateTime.Now.ToString());
                            }
                        }
                        _ipEndPointTimeList.Remove(phoneNumber);
                        _ipEndPointList.Remove(phoneNumber);


                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("AcceptMainForm.cs-515");
                    }

                }
                Invoke(new MethodInvoker(delegate()
                {
                    label_SokcetCount.Text = _ipEndPointList.Count.ToString(CultureInfo.InvariantCulture) + "," + DateTime.Now.ToString();
                }));


            }

        }



        private void InitControlAfterStopService()
        {
            spState.Text = @" 监听服务未启动 ...";
            button_startListening.Enabled = true;
            button_stopListening.Enabled = false;
            textBox_ChinaNetIp.Enabled = true;
            textBox_UnicomIp.Enabled = true;
            textBox_DataBaseHandlerThreadCount.Enabled = true;
            textBox_DataHandlerThreadCount.Enabled = true;


            if (_threadDataHandler != null)
            {
                //终止所有的数据处理线程
                for (int i = 0; i < _dataHandlerThreadCount; i++)
                {
                    if (this._threadDataHandler[i].IsAlive) this._threadDataHandler[i].Abort();
                }
            }







            //if (_addTaxiGpsHistoryInfoQueue != null) _addTaxiGpsHistoryInfoQueue.Abort();
            if (_ipEndPointClearThread != null) _ipEndPointClearThread.Abort();

            // if (_server != null) { _server.Stop(); }
        }



        private void InitControlAfterStartService()
        {
            spState.Text = @" 监听服务已启动 ...";
            button_startListening.Enabled = false;
            button_stopListening.Enabled = true;
            textBox_ChinaNetIp.Enabled = false;
            textBox_UnicomIp.Enabled = false;
            textBox_DataBaseHandlerThreadCount.Enabled = false;
            textBox_DataHandlerThreadCount.Enabled = false;


        }







        private void button_startListening_Click(object sender, EventArgs e)
        {

            if (!CommonRoutine.IsValidIp(textBox_ChinaNetIp.Text))
            {
                MessageBox.Show(@"请检查接入服务器IP1格式");
                textBox_ChinaNetIp.Focus();
                return;
            }
            if (!CommonRoutine.IsValidIp(textBox_UnicomIp.Text))
            {
                MessageBox.Show(@"请检查接入服务器IP2格式");
                textBox_UnicomIp.Focus();
                return;
            }


            if (!int.TryParse(textBox_DataBaseHandlerThreadCount.Text, out _dataBaseHandlerThreadCount))
            {
                MessageBox.Show(@"数据库处理线程数：  请输入数字");
                textBox_DataBaseHandlerThreadCount.Focus();
                return;
            }
            if (!int.TryParse(textBox_DataHandlerThreadCount.Text, out _dataHandlerThreadCount))
            {
                MessageBox.Show(@"网络数据处理线程数 ：请输入数字");
                textBox_DataHandlerThreadCount.Focus();
                return;
            }
            StartServecie();

        }

        private void button_stopListening_Click(object sender, EventArgs e)
        {

            try
            {
                _ipEndPointList.Clear();
                _ipEndPointTimeList.Clear();
                label_SokcetCount.Text = "0";
                InitControlAfterStopService();

            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("AcceptMainForm.cs-891");
            }

        }

        private void HideServer_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
            ShowInTaskbar = false;
            Visible = false;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            button_startListening.Enabled = true;
            button_stopListening.Enabled = false;
            string[] config = OperateConfig.GetAcceptServerConfig();
            if (config != null)
            {
                textBox_ChinaNetIp.Text = config[0];
                textBox_UnicomIp.Text = config[1];

            }
            //  StationsBusDs = CXmlFileToDataSet("s.xml");
            //double theCenterLat = 29.23251;
            //double theCenterLng = 115.80896;
            //BusInfo b = new BusInfo();
            //b.IMEI = "0234567890123456";
            //b.PreStation = "人民医院";
            //b.CurrentStation = "南大红绿灯";

            //b.Latitude = 29.25050 + 0.00239;
            //b.Longitude = 115.79338 - 0.00547;
            //b.BusName = "1路 外";

            //BusiList[b.IMEI] = b;
            //// CalculatorBusGpsInWhichStation(b);

            //BusInfo b1 = new BusInfo();
            //b1.IMEI = "0234567890123457";
            //b1.PreStation = "金贸广场";
            //b1.CurrentStation = "共青中心城";
            //b1.BusName = "1路 内";
            //b1.Latitude = 29.25038 + 0.00239;
            //b1.Longitude = 115.78021 - 0.00547;
            //BusiList[b1.IMEI] = b1;

            ////  CalculatorBusGpsInWhichStation(b1);


            //BusInfo b2 = new BusInfo();
            //b2.IMEI = "0234567890123458";
            //b2.PreStation = "工商局";
            //b2.CurrentStation = "金贸广场";
            //b2.BusName = "2路";
            //b2.Latitude = 29.23593 + 0.00239;
            //b2.Longitude = 115.80920 - 0.00547;
            //BusiList[b2.IMEI] = b2;

            //   CalculatorBusGpsInWhichStation(b2);


            StartServecie();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                _ipEndPointList.Clear();
                label_SokcetCount.Text = "0";

                InitControlAfterStopService();

            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("AcceptMainForm.cs-943");
            }
            notifyIcon1.Visible = false;
            Environment.Exit(0);
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                WindowState = FormWindowState.Normal;
                ShowInTaskbar = true;
                Visible = true;
                Focus();
            }
            else
            {
                WindowState = FormWindowState.Minimized;
                ShowInTaskbar = false;
                Visible = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string showtext = string.Empty;

            lock (_ipEndPointList.SyncRoot)
            {
                foreach (DictionaryEntry dictionaryEntry in _ipEndPointList)
                {
                    if (dictionaryEntry.Key.ToString().Length == 12)
                    {
                        showtext = showtext + "PhoneNumber : =" + dictionaryEntry.Key + Environment.NewLine;
                    }
                }
            }
            richTextBox1.Text = showtext;
            //  MessageBox.Show(showtext);
        }







        public static DataSet CXmlFileToDataSet(string xmlFilePath)
        {
            if (!string.IsNullOrEmpty(xmlFilePath))
            {
                string path = xmlFilePath;
                StringReader StrStream = null;
                XmlTextReader Xmlrdr = null;
                try
                {
                    XmlDocument xmldoc = new XmlDocument();
                    //根据地址加载Xml文件
                    xmldoc.Load(path);
                    DataSet ds = new DataSet();
                    //读取文件中的字符流
                    StrStream = new StringReader(xmldoc.InnerXml);
                    //获取StrStream中的数据
                    Xmlrdr = new XmlTextReader(StrStream);
                    //ds获取Xmlrdr中的数据
                    ds.ReadXml(Xmlrdr);
                    return ds;
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    //释放资源
                    if (Xmlrdr != null)
                    {
                        Xmlrdr.Close();
                        StrStream.Close();
                        StrStream.Dispose();
                    }
                }
            }
            else
            {
                return null;
            }
        }



        #region CRC校验
        /**
         * 获取计算好的CRC值
         * 
         * @return
         */
        public int getCrcValue()
        {
            return ~value & 0xffff;
        }



        private void SetCRC(ref byte[] sendbyte)
        {
            byte[] crcBytes = new byte[4];
            Array.Copy(sendbyte, 2, crcBytes, 0, 4);

            update(crcBytes);

            int dsds = getCrcValue();
            byte[] sdsd = BitConverter.GetBytes(dsds);

            value = 0xffff;
            sendbyte[6] = sdsd[1];
            sendbyte[7] = sdsd[0];
        }



        /**CRC值*/
        private int value = 0xffff;


        static int[] CRC16_TABLE =  {
		0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
	    0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
	    0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
	    0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
	    0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
	    0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
	    0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
	    0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
	    0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
	    0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
	    0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
	    0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
	    0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
	    0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
	    0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
	    0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
	    0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
	    0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
	    0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
	    0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
	    0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
	    0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
	    0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
	    0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
	    0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
	    0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
	    0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
	    0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
	    0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
	    0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
	    0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
	    0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
	};

        /**
         * 计算一个字节数组的CRC值
         * @param data
         */
        public void update(byte[] data)
        {
            //int fcs = 0xffff;
            for (int i = 0; i < data.Length; i++)
            {
                // 1.value 右移8位(相当于除以256)
                // 2.value与进来的数据进行异或运算后再与0xFF进行与运算
                //    得到一个索引index，然后查找CRC16_TABLE表相应索引的数据
                // 1和2得到的数据再进行异或运算。
                value = (value >> 8) ^ CRC16_TABLE[(value ^ data[i]) & 0xff];
            }
            // 取反
            //return ~fcs;
        }
        #endregion

        private void button_SendAD_Click(object sender, EventArgs e)
        {

            string adContent = OperateConfig.GetAdContent();
            byte[] mbodydata = Encoding.GetEncoding("GBK").GetBytes(adContent);
            byte[] mHead = OperateAgreement.GetMessageHead(ConstParameters.CmdSendAD, false, false, mbodydata.Length, new byte[6],
                              new byte[2], 0, 0);
            byte[] tempData1 = OperateAgreement.PackageSendData(mHead, mbodydata);

            lock (_ipEndPointList.SyncRoot)
            {
                foreach (var obj in _ipEndPointList.Values)
                {
                    IPEndPoint ipEndPoint = obj as IPEndPoint;
                    if (ipEndPoint != null && _udpClientChinaNet != null && _udpClientUniCom != null)
                    {

                        _udpClientChinaNet.SendTo(tempData1, tempData1.Length, SocketFlags.None, ipEndPoint);
                        _udpClientUniCom.SendTo(tempData1, tempData1.Length, SocketFlags.None, ipEndPoint);
                    }
                }
            }

        }


    }

}
